package com.yao.nettydemo.wechat;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import java.util.Scanner;

/**
 * @author Henry Yao
 * @date 2021/5/3
 */
public class WeChatClientHandler extends SimpleChannelInboundHandler<String> {
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        // 需要新建一个线程进行读操作
        new Thread(() -> {
            System.out.println("已上线，请发送消息...(Q退出)");
            while (true) {
                Scanner scanner = new Scanner(System.in);
                String next = scanner.next();
                if ("Q".equals(next)) {
                    ctx.channel().close();
                    break;
                }
                ctx.writeAndFlush(next + "\r\n");
            }
        }, "send").start();
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
        System.out.println(msg);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.close();
    }
}
